import pyautogui
from pynput import mouse, keyboard
import threading
import time

# 标记鼠标侧键1是否被按下
side_button_pressed = False

# 创建一个键盘控制器
keyboard_controller = keyboard.Controller()

# 创建一个事件对象
key_event = threading.Event()

def key_press_loop():
    global side_button_pressed
    while True:
        key_event.wait()  # 等待事件被设置
        while side_button_pressed:
            keyboard_controller.tap('t')
            time.sleep(0.1)
            if side_button_pressed:
                keyboard_controller.tap('2')
                time.sleep(0.1)
            else:
                break

            if side_button_pressed:
                keyboard_controller.tap('r')
                time.sleep(0.1)
            else:
                break

            if side_button_pressed:
                if pyautogui.pixel(2416, 1275) == (255, 255, 255):
                    time.sleep(0.1)
                    keyboard_controller.tap('f')
                    time.sleep(0.1)
            else:
                break

            if side_button_pressed:
                if pyautogui.pixel(2416, 1275) == (255, 255, 255):
                    keyboard_controller.tap('f')
                    time.sleep(0.1)
            else:
                break

            if side_button_pressed:
                keyboard_controller.tap('t')
                time.sleep(0.1)
            else:
                break

            if side_button_pressed:
                if pyautogui.pixel(2416, 1275) == (255, 255, 255):
                    time.sleep(0.1)
                    keyboard_controller.tap('f')
                    time.sleep(0.1)
            else:
                break

        key_event.clear()  # 清除事件

def mouse_listener():
    global side_button_pressed
    with mouse.Listener(on_click=on_click) as listener:
        listener.join()

def on_click(x, y, button, pressed):
    global side_button_pressed
    if button == mouse.Button.x2:
        side_button_pressed = pressed
        if side_button_pressed:
            key_event.set()  # 设置事件
        else:
            key_event.clear()  # 清除事件

# 启动鼠标监听线程
mouse_thread = threading.Thread(target=mouse_listener, daemon=True)
mouse_thread.start()

# 启动按键循环线程
key_press_thread = threading.Thread(target=key_press_loop, daemon=True)
key_press_thread.start()
# 保持主程序运行
mouse_thread.join()
key_press_thread.join()
